package com.example.demotest.controller;

import com.example.demotest.pojo.ResponseMessage;
import com.example.demotest.pojo.dto.AddressDto;
import com.example.demotest.pojo.Address;
import com.example.demotest.service.AddressService;

import com.example.demotest.util.JWT;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/address")
public class AddressController {

    @Autowired
    private AddressService addressService;

    @Autowired
    private JWT jwt;

    /**
     * 获取当前用户的所有地址列表
     */
    @GetMapping("/info")
    public ResponseMessage<List<AddressDto>> getAllAddresses(HttpServletRequest request) {
        String token = jwt.extractToken(request);  // 从请求中提取 token
        Integer userId = jwt.getUserIdFromToken(token);

        List<AddressDto> addresses = addressService.getAllAddresses(userId);
        return ResponseMessage.success(addresses);
    }

    /**
     * 新增地址（最多5个）
     */
    @PostMapping("/add")
    public ResponseMessage<AddressDto> addAddress(@RequestBody AddressDto addressDto, HttpServletRequest request) {
        String token = jwt.extractToken(request);  // 从请求中提取 token
        Integer userId = jwt.getUserIdFromToken(token);

        addressDto.setUserId(userId);
        System.out.println(userId);

        if (addressService.countByUserId(userId) >= 5) {
            return ResponseMessage.error(400, "已达到最大地址数量！");
        }

        // 新增的判断：查重
        boolean isDuplicate = addressService.isDuplicateAddress(addressDto);
        if (isDuplicate) {
            return ResponseMessage.error(400, "该地址信息已存在，不能重复添加！");
        }

        AddressDto newAddress = addressService.addAddress(addressDto);
        return ResponseMessage.success(newAddress);
    }

    /**
     * 更新地址
     */
    @PutMapping("/update")
    public ResponseMessage<AddressDto> updateAddress(@RequestBody AddressDto addressDto, HttpServletRequest request) {
        String token = jwt.extractToken(request);  // 从请求中提取 token
        Integer userId = jwt.getUserIdFromToken(token);


        addressDto.setUserId(userId);
        AddressDto updated = addressService.updateAddress(addressDto);
        return ResponseMessage.success(updated);
    }

    /**
     * 删除地址
     */
    @DeleteMapping("/delete")
    public ResponseMessage<Void> deleteAddress(@RequestBody AddressDto addressDto, HttpServletRequest request) {
        String token = jwt.extractToken(request);  // 从请求中提取 token
        Integer userId = jwt.getUserIdFromToken(token);

        Integer id = addressDto.getId();
        addressService.deleteAddress(userId, id);
        return ResponseMessage.success();
    }
}
